import React, { useEffect, useRef, useState } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Button, Checkbox, Popconfirm, Switch, Tag, Image, FormInstance } from 'antd';
import type { ProColumns } from '@ant-design/pro-table';
import ProTable, { ActionType } from '@ant-design/pro-table';
import { getShopGoods } from '@/services/shop/api';
import { 
  getCategoryListByPage,
  getBrandListByPage
 } from '@/services/stock-goods/api';
 import { 
  deleteShopGoods,
  updateShopGoodsStatus
 } from '@/services/shop/api';
 import { getMallTag } from '@/services/mall/api';
import { PlusOutlined } from '@ant-design/icons';
import OptForm from './OptForm';
import { history, useModel } from 'umi';
import { MsgType, showMsg, getTag, isExits, replaceImgHost } from '@/utils/utils';
import PermissionControl from '@/components/PermissionControl';
import BreadcrumbDept from '@/components/BreadcrumbDept';
import './style.less';

interface IndexProps {
  location?: any;
}

const ShopGoodsList: React.FC<IndexProps> = (props) => {
  const { location } = props;
  const { query } = location;
  const { goods_status, flag } = query;

  const [visible, setVisible] = useState<boolean>(false);
  const [imgVisible, setImgVisible] = useState<boolean>(false);
  const [classList, setClassList] = useState<STOCKGOODSAPI.CategoryItem[]>([]);
  const [brandList, setBrandList] = useState<STOCKGOODSAPI.BrandItem[]>([]);
  const [checked, setChecked] = useState<boolean>(false);
  const [tagList, setTagList] = useState<MALLAPI.MallTag[]>([]);
  const columns: ProColumns<SHOPAPI.ShopGoods>[] = [
    {
      title: '库存分类',
      dataIndex: 'class_id',
      hideInTable: true,
      valueType: 'select',
      fieldProps: {
        options: classList.map(item => {
          return {
            label: item.class_name as string,
            value: item.class_id as string
          }
        }),
        showSearch: true
      }
    },
    {
      title: '商品品牌',
      dataIndex: 'brand_id',
      hideInTable: true,
      valueType: 'select',
      fieldProps: {
        options: brandList.map(item => {
          return {
            label: item.brand_name as string,
            value: item.brand_id as string
          }
        }),
        showSearch: true
      }
    },
    {
      title: '图片',
      dataIndex: 'attach_list',
      search: false,
      align: 'center',
      width: 100,
      render: (dom, entity) => {
        const attach_list = entity.attach_list.filter(item => !item.attach_thumb_url.endsWith('.mp4'))
        return <div style={{ maxWidth: '100%', width: 'auto', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <Image
            preview={false}
            // width={100}
            height={60}
            src={replaceImgHost(attach_list[0]?.attach_thumb_url)}
          />
          <div style={{ display: 'none' }}>
            <Image.PreviewGroup preview={{ visible: imgVisible, onVisibleChange: vis => setImgVisible(vis) }}>
              {
                attach_list.map(item => {
                  return <Image style={{ maxWidth: '100%', width: 'auto' }} key={item.attach_id} src={replaceImgHost(item.attach_url)}/>
                })
              }
            </Image.PreviewGroup>
          </div>
        </div>
      }
    },
    {
      title: '品牌',
      dataIndex: 'brand_name',
      width: 120,
      search: false
    },
    {
      title: '名称',
      dataIndex: 'shop_goods_name',
      search: false,
      width: 200
    },
    {
      title: '商品编号',
      dataIndex: 'goods_id',
      className: 'wordbreak',
      width: 120,
      fieldProps: {
        placeholder: '输入完整商品编号',
      }
    },
    {
      title: '商品名称',
      dataIndex: 'shop_goods_name',
      hideInTable: true,
      fieldProps: {
        placeholder: '拼音首字母/文字',
      }
    },
    {
      title: '标签',
      dataIndex: 'tag_list',
      search: false,
      width: 175,
      render: (_, record) => {
        const list: string[] = [];
        record.tag_list.forEach(tag => {
          tagList.forEach(tag2 => {
            if (tag2.tag_id === tag.tag_id) {
              list.push({
                tag_id: tag2.tag_id,
                tag_name: tag2.tag_name,
              });
            }
          })
        })
        return list.map(tag => {
          return <Tag key={tag} style={{marginBottom: list.length > 2 ? 4 : 0}} color={getTag(tag.tag_id)}>{tag.tag_name}</Tag>
        });
      }
    },
    {
      title: '库存',
      dataIndex: 'total_inventory',
      width: 80,
      align: 'right',
      search: false
    },
    {
      title: '销量',
      dataIndex: 'total_salves_volume',
      width: 100,
      align: 'right',
      search: false
    },
    // {
    //   title: '排序',
    //   dataIndex: 'sort',
    //   width: 70,
    //   align: 'right',
    //   search: false
    // },
    {
      title: '上架状态',
      dataIndex: 'goods_status',
      align: 'center',
      valueType: 'select',
      valueEnum: {
        O: '上架',
        D: '下架'
      },
      width: 70,
      render: (_, record) => {
        return isExits('600602005') ? <React.Fragment>
          <Popconfirm 
            title={record.goods_status === 'O' ? '下架后商品将不在商城中展示，是否继续？' : '上后商品在商城中正常销售，是否继续？'}
            onConfirm={async() => {
              try {
                await updateShopGoodsStatus([record.shop_goods_id], record.goods_status === 'O' ? 'D' : 'O', true);
                showMsg(record.goods_status === 'O' ? '已下架' : '已上架', MsgType.SUCCESS);
                actionRef.current?.reload();
              } catch (error) {
                showMsg(error?.data?.errmsg);
              }
            }}>
            <Switch checked={record.goods_status === 'O'} />
          </Popconfirm>
      </React.Fragment> : _
      }
    },
    {
      dataIndex: 'flag',
      hideInTable: true,
      renderFormItem: (_, { type, defaultRender, ...rest },form) => {
        if (type === 'form') {
          return null;
        }
        return <Checkbox 
                checked={checked} 
                onChange={(event: any) => setChecked(event.target.checked)}>只查看库存告警商品</Checkbox>;
      }
    },
    {
      title: '操作',
      width: 100,
      align: 'center',
      valueType: 'option',
      render: (_, record) => {
        return [
          <PermissionControl key="edit">
            <a onClick={() => {
              history.push({
                pathname: '/shop/goods/edit',
                query: {
                  shop_goods_id: record.shop_goods_id
                }
              });
            }}>编辑</a>
          </PermissionControl>,
          <PermissionControl key="delete" action_id="600602007">
            <Popconfirm 
              placement="topRight"
              okText="确认删除"
              cancelText="再想想"
              onConfirm={async () => {
                try {
                  await deleteShopGoods([record.shop_goods_id], true);
                  actionRef.current?.reload();
                } catch (error) {
                  showMsg(error?.data?.errmsg);
                }
              }}
              title="删除后商品将不在商城中展示，是否继续？">
              <a>删除</a>
            </Popconfirm>
          </PermissionControl>
          
        ]
      }
    }
  ];
  const [selectedKeys, setSelectedKeys] = useState<React.Key[]>([]);
  const actionRef = useRef<ActionType>();
  const formRef = useRef<FormInstance>();
  const { initialState }  = useModel('@@initialState');

  useEffect(() => {
    getCategoryListByPage({
      current: 1,
      pageSize: 10000
    }).then((data: STOCKGOODSAPI.CategoryItemList) => {
      const list = data.record_list.filter(item => item.create_dept_code === initialState?.currentUser?.dept_code)
      setClassList(list || []);
    }).catch(error => {
      showMsg(error?.data?.errmsg)
    });

    getBrandListByPage({
      current: 1,
      pageSize: 10000
    }).then((data: STOCKGOODSAPI.BrandItemList) => {
      const list = data.record_list.filter(item => item.create_dept_code === initialState?.currentUser?.dept_code)
      setBrandList(list || []);
    }).catch(error => {
      showMsg(error?.data?.errmsg)
    });

    getMallTag().then((data: MALLAPI.MallTag[]) => {
      setTagList(data);
    });
  }, []);

  useEffect(() => {
    if (goods_status || flag) {
      formRef.current?.setFieldsValue({
        goods_status,
        flag
      });

      if (flag === '1') {
        setChecked(true);
      } else {
        setChecked(false);
      }
    }
    formRef.current?.submit();
  }, [goods_status, flag])

  return (
    <PageContainer extra={[
      <BreadcrumbDept />
     ]} breadcrumb={{}}>
      <ProTable<SHOPAPI.ShopGoods, SHOPAPI.ShopGoods & COMMON.PageParams & { flag?: string; }>
        rowKey="shop_goods_id"
        bordered
        manualRequest={true}
        formRef={formRef}
        actionRef={actionRef}
        className='shop-goods-table'
        request={async (params) => {
          if (checked) {
            params.flag = '1';
          }
          console.log(params);
          try {
            const data: SHOPAPI.ShopGoodsList = await getShopGoods(params);
            return {
              data: data.record_list,
              total: data.sum_record_num,
              success: true
            }
          } catch (error) {
            showMsg(error?.data?.errmsg);
            return {
              data: [],
              total: 0,
              success: true
            }
          }
        }}
        search={{
          span: 6,
          collapsed: false,
          collapseRender: () => '',
          optionRender: (searchConfig, formProps, dom) => {
            dom.shift();
            return dom;
          }
        }}
        toolbar={{
          menu: {
            type: 'inline',
            items: [
              {
                key: 'add',
                label: <PermissionControl action_id="600602001">
                    <Button 
                      onClick={() => {
                        setVisible(true);
                      }} 
                      icon={<PlusOutlined />} 
                      type="primary">
                      新增
                    </Button>
                </PermissionControl>
              },
              {
                key: 'delete',
                label: <PermissionControl action_id="600602002">
                    <Popconfirm 
                      onConfirm={async () => {
                        try {
                          await deleteShopGoods(selectedKeys as string[]);
                          showMsg('已删除', MsgType.SUCCESS);
                          actionRef.current?.clearSelected?.();
                          actionRef.current?.reload();
                        } catch (error) {
                          showMsg(error?.data?.errmsg);
                        }
                      }}
                      okText="确认删除"
                      cancelText="再想想"
                      disabled={selectedKeys.length === 0}
                      title="删除后商品将不在商城中展示，是否继续？">
                    <Button disabled={selectedKeys.length === 0} type="primary">批量删除商品</Button>
                  </Popconfirm>
                </PermissionControl>
              },
              {
                key: 'put-on-the-shelf',
                label: <PermissionControl action_id="600602003">
                      <Popconfirm 
                        onConfirm={async () => {
                          try {
                            await updateShopGoodsStatus(selectedKeys as string[], 'O');
                            // @ts-ignore
                            actionRef.current?.clearSelected();
                            actionRef.current?.reload();
                          } catch (error) {
                            showMsg(error?.data?.errmsg);
                          }
                        }}
                        disabled={selectedKeys.length === 0}
                        okText="确认上架"
                        cancelText="再想想"
                        title="上后商品在商城中正常销售，是否继续？">
                        <Button disabled={selectedKeys.length === 0} type="primary">
                          批量上架商品
                        </Button>
                    </Popconfirm>
                </PermissionControl>
              },
              {
                key: 'off-shelf',
                label: <PermissionControl action_id="600602004">
                        <Popconfirm 
                        onConfirm={async () => {
                          try {
                            await updateShopGoodsStatus(selectedKeys as string[], 'D');
                            // @ts-ignore
                            actionRef.current?.clearSelected();
                            actionRef.current?.reload();
                          } catch (error) {
                            showMsg(error?.data?.errmsg);
                          }
                        }}
                        okText="确认下架"
                        cancelText="再想想"
                        disabled={selectedKeys.length === 0}
                        title="下架后商品在商城中置灰展示，是否继续？">
                          <Button disabled={selectedKeys.length === 0} type="primary">
                            批量下架商品
                          </Button>
                      </Popconfirm>
                    </PermissionControl>
              }
            ]
          }
        }}
        pagination={{
          showQuickJumper: true
        }}
        options={false}
        rowSelection={{
          onChange: (selectedKeys) => {
            setSelectedKeys(selectedKeys);
          }
        }}
        // scroll={{
        //   x: 1200
        // }}
        columns={columns}
      />
      
      {
        visible && <OptForm handleModalVisible={setVisible} />
      }
    </PageContainer>
  );
};
export default ShopGoodsList;
